# Create your views here.
import random
from django.views.decorators.csrf import csrf_exempt 
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.template import Context, loader
from django.http import Http404
from randomMedia.models import Media, Vote
from settings import MEDIA_ROOT
from models import User
from django.contrib.auth import authenticate, login

@csrf_exempt
def display(request):
    t = loader.get_template('randomMedia/display.html')
    files = list(Media.objects.all())
    if(len(files) == 0):
        raise Http404 
    index = random.randint(0, len(files) - 1)
    mediaFile = files[index]
    c = Context({
        'mediaFile': mediaFile,
        })
    return HttpResponse(t.render(c))


def results(request, mediaFile_id):
    p = get_object_or_404(Media, pk=mediaFile_id)
    return render_to_response('randomMedia/results.html', {'mediaFile': p})

def preLogin(request):
    username = ""
    state = "Please log in below..."
    return render_to_response('randomMedia/login.html', {'state':state, 'username': username})
    
    
    
def userLogin(request):
    state = ""
    username = password = ''
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return render_to_response('randomMedia/upload.html', {'state':state, 'username': username, 'user': user})
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."

    return render_to_response('randomMedia/login.html', {'state':state, 'username': username})

def vote(request, mediaFile_id):
    p = get_object_or_404(Media, pk=mediaFile_id)
    vList = Vote.objects.filter(file__id=p.id, value = request.POST['choice'])
    if(len(vList) <= 0):
        v = Vote(value = request.POST['choice'], file = p, count = 1)    
    else:
        v = vList[0]
        v.count +=1
    v.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
    return HttpResponseRedirect(reverse('randomMedia.views.results', args=(p.id,)))

# rewrite this
def uploadMedia(request):
    if (request.method == 'POST') and request.user.is_authenticated():
        file = handle_uploaded_file( request.FILES['datafile'], request.POST['textline'], request.user)
        return HttpResponseRedirect('/randomMedia/')
    else:
        username = ''
        state = 'Upload failed, please re-Log...'
        return render_to_response('randomMedia/login.html', {'state':state, 'username': username})

#not a view
def handle_uploaded_file(f, fName, user):
    destination = open(MEDIA_ROOT + '/' + fName +'.jpg', 'wb')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
    mediaFile = Media(profile = user.get_profile(), file = f, name = fName, isActive = True)
    mediaFile.save()
